package com.yeyks.apppay.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.service.WxPayService;
import com.yeyks.dal.domain.RechargeRecord;
import com.yeyks.exception.ServiceException;
import com.yeyks.service.RechargeRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author fuchangshuai
 * @date 2019/5/6 0006
 */
@RestController
@Slf4j
@ApiIgnore
public class WxPayCallbackNewController {

    @Autowired
    private WxPayService payService;
    @Autowired
    private RechargeRecordService rechargeRecordService;

    private ExecutorService executorService = Executors.newFixedThreadPool(20);

    /**
     * 微信推广充值回调
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/rechangeCallback")
    public String rechangeCallback(HttpServletRequest request, HttpServletResponse response) {
        try {
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            WxPayOrderNotifyResult resultCode = payService.parseOrderNotifyResult(xmlResult);
            if (resultCode == null) {
                return WxPayNotifyResponse.fail("返回结果为空");
            }
            checkRechange(resultCode);
            String outTradeNo = resultCode.getOutTradeNo();
            // 另起线程处理业务
            log.info("另起线程处理业务");
            executorService.execute(() -> {
                // 支付成功
                if (resultCode.getResultCode().equals("SUCCESS")) {
                    log.info("支付成功");
                    // 处理支付成功修改状态为待入住
                    rechargeRecordService.payCallback(outTradeNo, true);
                } else {
                    log.info("支付失败");
                    rechargeRecordService.payCallback(outTradeNo, false);
                }
            });
            return WxPayNotifyResponse.success("处理成功!");
        } catch (Exception e) {
            log.error("微信回调结果异常,异常原因{}", e.getMessage());
            return WxPayNotifyResponse.fail(e.getMessage());
        }
    }

    private void checkRechange(WxPayOrderNotifyResult resultCode) throws ServiceException {
        String outTradeNo = resultCode.getOutTradeNo();
        // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        RechargeRecord rechargeRecord = rechargeRecordService.selectOrderByOrderNo(outTradeNo);
        if (rechargeRecord == null) {
            throw new ServiceException("out_trade_no错误");
        }
        // 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        Integer totalAmount = resultCode.getTotalFee();
        log.info("totalAmount{}", totalAmount);
        if (!totalAmount.equals(rechargeRecord.getPayAmount())) {
            throw new ServiceException("total_amount错误");
        }
    }
}
